﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrawlerCore;
using WapCrawler.Classes;
using Google.GData.Client;

namespace WapCrawler.Testing
{
    public partial class frmBloggerAPI : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Buoc 1: Yeu cau lay Authorization Token
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAuthorization_Click(object sender, EventArgs e)
        {
            string authUrl = "https://accounts.google.com/o/oauth2/auth";
            string param = string.Format(
                    "scope={0}&state={1}&access_type={2}&redirect_uri={3}&response_type=code&client_id={4}", "https://www.googleapis.com/auth/blogger", "blogger", "offline",
                    "http://localhost:2132", "603803809062.apps.googleusercontent.com");
            txtAuthorizationCode.Text = string.Format("{0}?{1}", authUrl, param);
            
            //HttpWebRequest req = (HttpWebRequest)WebRequest.Create(txtAuthorizationCode.Text);
            //req.Method = "GET";

            //HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            ////Response.Write(((HttpWebResponse)resp).StatusDescription);
            //Stream responseStream = resp.GetResponseStream();
            //StreamReader responseStreamReader = new StreamReader(responseStream);
            //txtAuthorizationCode.Text = responseStreamReader.ReadToEnd();//parse token from result
        }

        public void FunctionTest1()
        {
            string param = string.Format(
                    "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", txtAuthorizationCode.Text,
                    "603803809062.apps.googleusercontent.com", "xxcW8SwZ_3KDvErxTp6tSGAV", System.Web.HttpUtility.UrlEncode("http://localhost:2132"));

            BrowserSession_General br = new BrowserSession_General();
            br.PostParams = "code=" + txtAuthorizationCode.Text +
                            "&client_id=603803809062.apps.googleusercontent.com&client_secret=xxcW8SwZ_3KDvErxTp6tSGAV&redirect_uri=" + System.Web.HttpUtility.UrlEncode("http://localhost:2132") + "&grant_type=authorization_code";
            br.Post("https://accounts.google.com/o/oauth2/token");
        }

        public void FunctionTest2()
        {
            byte[] buffer = Encoding.ASCII.GetBytes("code=" + txtAuthorizationCode.Text + "&client_id=603803809062.apps.googleusercontent.com&client_secret=xxcW8SwZ_3KDvErxTp6tSGAV&redirect_uri=" + System.Web.HttpUtility.UrlEncode("http://localhost:2132") + "&grant_type=authorization_code");
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
            req.Method = "POST";
            //req.Host = "accounts.google.com";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = buffer.Length;

            Stream strm = req.GetRequestStream();
            strm.Write(buffer, 0, buffer.Length);
            strm.Close();

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            //Response.Write(((HttpWebResponse)resp).StatusDescription);
            Stream responseStream = resp.GetResponseStream();
            StreamReader responseStreamReader = new StreamReader(responseStream);
            txtAuthorizationCode.Text = responseStreamReader.ReadToEnd();//parse token from result
        }
        /// <summary>
        /// Buoc 2: Yeu cau Access Token sau khi da co Authorization Token
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAccessToken_Click(object sender, EventArgs e)
        {
            FunctionTest2();
        }

        /** Creates a new blog entry and sends it to the specified Uri */
        public AtomEntry PostNewEntry(Service service, Uri blogPostUri)
        {
            //Console.WriteLine("\nPublishing a blog post");
            AtomCategory tag = new AtomCategory("Truyen", "http://www.blogger.com/atom/ns#");
            //tag.Label = "Truyen";
            AtomEntry createdEntry = null;
            if (blogPostUri != null)
            {
                // construct the new entry
                AtomEntry newPost = new AtomEntry();
                newPost.Title.Text = "Marriage!";
                newPost.Categories.Add(tag);
                newPost.Content = new AtomContent();
                newPost.Content.Content = "<div xmlns=\"http://www.w3.org/1999/xhtml\">" +
                    "<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>" +
                    "<p>He is the last man on earth I would ever desire to marry.</p>" +
                    "<p>Whatever shall I do?</p>" +
                    "</div>";
                newPost.Content.Type = "xhtml";
                newPost.Authors.Add(new AtomPerson());
                newPost.Authors[0].Name = "Elizabeth Bennet";
                newPost.Authors[0].Email = "liz@gmail.com";

                createdEntry = service.Insert(blogPostUri, newPost);
                if (createdEntry != null)
                {
                    Console.WriteLine("  New blog post created with title: " + createdEntry.Title.Text);
                }
            }
            return createdEntry;
        }

        /** Lists the user's blogs. */
        public void ListUserBlogs(Service service)
        {
            Console.WriteLine("\nRetrieving a list of blogs");
            FeedQuery query = new FeedQuery();
            // Retrieving a list of blogs
            query.Uri = new Uri("http://www.blogger.com/feeds/default/blogs");
            AtomFeed feed = null;
            feed = service.Query(query);
            foreach (AtomEntry entry in feed.Entries)
            {
                Console.WriteLine("  Blog title: " + entry.Title.Text);
            }
        }

        /** Lists the user's blogs and returns the URI for posting new entries
         * to the blog which the user selected.
         */
        public Uri SelectUserBlog(Service service)
        {
            //Console.WriteLine("\nPlease select a blog on which to post.");
            FeedQuery query = new FeedQuery();
            // Retrieving a list of blogs
            query.Uri = new Uri("http://www.blogger.com/feeds/default/blogs");
            AtomFeed feed = service.Query(query);

            // Publishing a blog post
            Uri blogPostUri = null;
            if (feed != null)
            {
                AtomEntry entry = feed.Entries[0];
                
                // Print out the title of the Blog
                Console.WriteLine("  Blog name: " + entry.Title.Text);
                //Console.Write("  Post to this blog? (y/n): ");
                //if (Console.ReadLine().Equals("y"))
                //{
                // find the href in the link with a rel pointing to the blog's feed
                for (int i = 0; i < entry.Links.Count; i++)
                {
                    if (entry.Links[i].Rel.Equals("http://schemas.google.com/g/2005#post"))
                    {
                        blogPostUri = new Uri(entry.Links[i].HRef.ToString());
                        //Console.WriteLine("  Your new posts will be sent to " + blogPostUri.AbsoluteUri.ToString());
                    }
                }
                //return blogPostUri;
                //}

            }
            return blogPostUri;
        }

        protected void btnCreatePost_Click(object sender, EventArgs e)
        {
            Google.GData.Client.Service service = new Service("blogger", "blogger-example");

            // ClientLogin using username/password authentication
            service.Credentials = new GDataCredentials(txtUsername.Text, txtPassword.Text);
            //ListUserBlogs(service);
            Uri blogPostUri = SelectUserBlog(service);
            AtomEntry createdEntry = PostNewEntry(service, blogPostUri);
            
            
            //PostAndDeleteNewDraftEntry(service, blogPostUri);
            //ListBlogEntries(service, blogPostUri);
            //ListBlogEntriesInDateRange(service, blogPostUri);
            //AtomEntry editedEntry = EditEntry(createdEntry);
            //DeleteEntry(editedEntry);
            //Uri commentPostUri = SelectBlogEntry(service, blogPostUri);
            //AtomEntry commentEntry = PostNewComment(service, commentPostUri);
            //ListEntryComments(service, commentPostUri);
            //DeleteComment(commentEntry);

            //Console.WriteLine("Press enter to quit");
            //Console.ReadLine();

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            WapCrawler.Classes.BloggerSample obj = new BloggerSample();
            obj.MainProgram(new string[]{txtUsername.Text, txtPassword.Text});
        }
    }
}